package com.lekang.le.service.impl;

import com.lekang.ZcqEntity.CarerSetDTO;
import com.lekang.le.mapper.CaregiverBedBindingZcqMapper;
import com.lekang.le.mapper.SysUserZcqMapper;
import com.lekang.le.service.CarerBedService;
import com.lekang.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.lekang.le.mapper.bedZcqMapper;
import org.springframework.transaction.annotation.Transactional;


@Service
public class CarerBedServiceImpl implements CarerBedService {
    @Resource
    private SysUserZcqMapper sysUserZcqMapper;
    @Resource
    private bedZcqMapper bedZcqMapper;
    @Resource
    private CaregiverBedBindingZcqMapper bindingMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setCarer(CarerSetDTO dto) {
// 步骤1：解析姓名字符串为列表（如"顾廷烨,盛明兰"→["顾廷烨","盛明兰"]）
        List<String> carerNameList = Arrays.stream(dto.getCarersStr().split(","))
                .map(String::trim)  // 去空格，防止前端传多空格
                .collect(Collectors.toList());

        // 步骤2：通过姓名查对应的user_id（关键：姓名转ID）
        List<Long> carerIdList = sysUserZcqMapper.selectUserIdsByNames(carerNameList);
        // 校验：如果查不到ID（比如姓名输错），抛异常
//        if (carerIdList.size() != carerNameList.size()) {
//            throw new RuntimeException("部分护理员姓名不存在，请检查");
//        }
        List<Long> bedIdList;
        if (dto.getIsBatch()) {
            bedIdList = bedZcqMapper.selectBedIdsByRoomNo(Integer.parseInt(dto.getRoomNo()));
        } else {
            Long bedId = bedZcqMapper.selectBedIdByRoomNoAndBedNo(Integer.parseInt(dto.getRoomNo()),Integer.parseInt( dto.getBedNo()));
            bedIdList = Arrays.asList(bedId);
        }
        // 删旧绑定
        for (Long bedId : bedIdList) {
            bindingMapper.deleteByBedId(bedId);
        }
        // 插新绑定
        for (Long bedId : bedIdList) {
            for (Long carerId : carerIdList) {

                bindingMapper.insert(bedId,carerId);
            }
        }

    }
}
